#include "client_base.h"
#include "time_module.h"
#include "retcodes.h"
#include "MessageDef.h"

namespace common
{

	CClientBase::CClientBase()
	{
		service_type_ = 0;
		service_id_ = 0;
		last_ping_time_ = 0;
	}

	CClientBase::~CClientBase()
	{

	}

	void CClientBase::OnMsgEvent()
	{
		static const uint32_t head_size = sizeof(CProxyHead);
		while (true)
		{
			if (input_streams_.Size() < sizeof(int32_t))
			{
				break;
			}
			//CProxyHead *head = (CProxyHead *)(input_streams_.ReadBuffer());
			//uint32_t total_size = head_size + head->msglen;
			//if (input_streams_.Size() < total_size)
			//{
			//	break;
			//}
			//if (head->msgid == ID_P2S_PING_RESPONSE)
			//{
			//	LOG_DEBUG("default", "ping response %s, server_type[%d]", FromUnixTime(head->extend),
			//		head->src_server_type);
			//}
			//else
			//{
			//	uint8_t *body_buffer = input_streams_.ReadBuffer() + head_size;
			//	dispatchMsg(*head, body_buffer, head->msglen);
			//}
			//input_streams_.AddReadBufSize(total_size);

			int8_t* buff = (int8_t*)(input_streams_.ReadBuffer());
			int32_t msg_len = 0;
			memcpy(&msg_len, buff, TY_MSG_HEAD_LEN);
			msg_len = ntohl(msg_len);

			if (input_streams_.Size() < TY_MSG_HEAD_LEN + TY_MSG_HEAD_LEN)
			{
				return ;
			}
			if (input_streams_.Size() < msg_len)
			{
				return;
			}
			on_msg(fd());
			input_streams_.AddReadBufSize(msg_len);
		}
		last_ping_time_ = CUR_SEC;
	}
	bool CClientBase::on_msg(uint32_t fd)
	{
		return true;
	}
	void CClientBase::OnConnect()
	{
		if (output_streams_.FreeSize() < sizeof(CProxyHead))
		{
			LOG_WARN("default", "output stream is not enough");
			return;
		}
		CProxyHead head;
		//head.src_gateway_id = server_gateway_id.value();
		head.src_server_type = service_type_;
		head.src_server_id = service_id_;
		*(CProxyHead *)(output_streams_.WriteBuffer()) = head;
		output_streams_.AddWriteBufSize(sizeof(CProxyHead));
		Flush();
		last_ping_time_ = CUR_SEC;
	}

	void CClientBase::OnDisconnect()
	{
		
	}

	int CClientBase::dispatchMsg(CProxyHead& head, uint8_t* buffer, uint32_t buffer_size)
	{
		LOG_WARN("default", "cant dispatch msg ");
		return -1;
	}

	int32_t CClientBase::SendPingMsg()
	{
		if (connected_ == false)
		{
			LOG_ERROR("default", "proxy is not connected");
			return ERR_UNKNOWN;
		}

		CProxyHead head;
		head.msg_id = PROXY_PING;
		head.extend = CUR_SEC;
		
		//std::string msg = "{\"msgid\":" + PROXY_PING; msg +="}";

		//::common::CNetMsgTransfer::out_tcp_for_proxy(*this, head, msg.c_str(), msg.length());
		return ::common::SUCCEED;
	}

	int32_t CClientBase::SendMsg(::common::CProxyHead& proxy_head, const std::string& msg)
	{
		if (connected_ == true)
		{
			::common::CNetMsgTransfer::out_tcp_for_proxy(*this, proxy_head, msg.c_str(), msg.length());

			return ::common::SUCCEED;
			
		}
		else
		{
			LOG_WARN("default", "proxy is not connected %s:%d", ip(), port());
		}
		return ERR_UNKNOWN;

	}
}